#使用 PyQT这个 GUI 库，将命令行界面改为图形化界面，提升用户体验。
import os.path
import time
from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget

def calculate_bmr(gender, weight, height, age):
    """计算基础代谢率（BMR）。
    参数：
    gender -- 性别，取值为 "男" 或 "女"。
    weight -- 体重，单位为公斤。
    height -- 身高，单位为厘米。
    age -- 年龄，单位为岁。
    返回值：
    BMR 的数值，单位为千卡/天。
    """
    if gender == "男":
        bmr = 13.7 * weight + 5.0 * height - 6.8 * age + 66
    elif gender == "女":
        bmr = 9.6 * weight + 1.8 * height - 4.7 * age + 655
    else:
        raise ValueError("性别输入错误，请重新输入！")

    if bmr <= 0:
        raise ValueError("计算错误，请检查输入数据是否正确！")
    else:
        return bmr

def save_bmr_data(data_file, data):
    with open(data_file, 'a') as f:
        f.write(','.join(str(x) for x in data) + '\n')

class BmrCalculator(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
    def init_ui(self):
        gender_label = QLabel("性别:")
        self.gender_edit = QLineEdit()
        weight_label = QLabel("体重(kg):")
        self.weight_edit = QLineEdit()
        height_label = QLabel("身高(cm):")
        self.height_edit = QLineEdit()
        age_label = QLabel("年龄:")
        self.age_edit = QLineEdit()
        self.result_label = QLabel("")
        calculate_button = QPushButton("计算BMR")
        calculate_button.clicked.connect(self.calculate_bmr_clicked)

        vbox = QVBoxLayout()
        vbox.addWidget(gender_label)
        vbox.addWidget(self.gender_edit)
        vbox.addWidget(weight_label)
        vbox.addWidget(self.weight_edit)
        vbox.addWidget(height_label)
        vbox.addWidget(self.height_edit)
        vbox.addWidget(age_label)
        vbox.addWidget(self.age_edit)
        vbox.addWidget(calculate_button)
        vbox.addWidget(self.result_label)
        self.setLayout(vbox)
        self.setWindowTitle("BMR计算器")

    def calculate_bmr_clicked(self):
        gender = self.gender_edit.text().strip()
        weight_str = self.weight_edit.text().strip()
        height_str = self.height_edit.text().strip()
        age_str = self.age_edit.text().strip()

        try:
            weight = float(weight_str)
            height = float(height_str)
            age = int(age_str)
            if not (30 <= weight <= 300) or not (100 <= height <= 250) or not (10 <= age <= 150):
                raise ValueError("输入有误，请重新输入正确的数据！体重范围为 30kg - 300kg，身高范围为 100cm - 250cm，年龄范围为 10岁 - 150岁。")
            bmr = calculate_bmr(gender, weight, height, age)
            now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            data = [now, gender, weight, height, age, bmr]
            data_file = "bmr_data.txt"
            if not os.path.exists(data_file):
                with open(data_file, 'w') as f:
                    f.write("时间,性别,体重(kg),身高(cm),年龄,BMR\n")
            save_bmr_data(data_file, data)
            self.result_label.setText("您的 BMR 值是 {:.2f} 千卡/天。".format(bmr))
        except ValueError as e:
            self.result_label.setText(str(e))

if __name__ == '__main__':
    app = QApplication([])
    calculator = BmrCalculator()
    calculator.show()
    app.exec_()